package com.core.jdbc;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlUtil {
    /**
     * 替换sql中的占位参数
     */
    public static String parseSql(String sql, Map<String, Object> params) {
        //匹配#{*}格式的占位参数
        String pString = "#\\{.*?\\}";
        String pString2 = ":[a-zA-Z0-9-_$#]*";
        Pattern pattern = Pattern.compile(pString2);
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
            String paraStr = matcher.group();
            int i = sql.indexOf(paraStr);
            //String paramName = paraStr.replaceAll("#\\{", "").replaceAll("}", "").trim();
            String paramName = paraStr.replaceAll(":", "").trim();

            if (params != null && i != -1) {
                Object param = params.get(paramName);

                String replace = "''";
                if (param == null) {
                    throw new MySqlException("取不到:" + paramName + "的值");
                }
                if (param instanceof String) {
                    //校验安全性
                    replace = "'" + param + "'";
                } else if (param instanceof List) {

                } else {
                    replace = param + "";
                }
                sql = sql.replace(paraStr, replace);

            }

        }
        return sql;
    }


    /**
     * 处理查询结果集
     *
     * @param set
     * @return
     * @throws SQLException
     */
    public static List<Map<String, Object>> handleResutSet(ResultSet set) throws SQLException {

        List<Map<String, Object>> list = new ArrayList<>();
        ResultSetMetaData rsmd = set.getMetaData();
        int count = rsmd.getColumnCount();
        //遍历查询结果
        while (set.next()) {
            Map<String, Object> map = new HashMap<String, Object>();
            for (int j = 1; j <= count; j++) {
                map.put(rsmd.getColumnName(j), set.getObject(j));
            }
            list.add(map);
        }
        return list;
    }
}
